#include "state_intro.h"
#include "krryn.h"

#include "texture_opengl.h"
#include "opengl.h"


#include "md5_builder.h"

using namespace krryn::math;
using namespace krryn::system;
using namespace krryn::system_imp;
using namespace krryn::usr;
using namespace krryn::data;
using namespace krryn::core;
using namespace krryn::scene;
using namespace krryn::view;
using namespace krryn::gui;

static state_intro _state_intro;

state_intro::~state_intro(){}

void state_intro::init(){
	// generic stuff that you always have to do
	system_info i;

	m_Manager = new job_manager(i.number_of_processors() - 2);
	m_Default = new default_renderer<api>(m_Manager);
	m_Camera  = new camera_fps();

	m_VB      = new vertex_buffer<api>(*m_Default->m_Renderer, 4);
	m_IB	  = new index_buffer<api>(*m_Default->m_Renderer, 6);

	{
		hardware_locker l_VertexRiaa(*m_VB, write);
		hardware_locker l_IndexRiaa(*m_IB, write);

		float s=1.f;
		float t=0.f;

		*m_VB += vertex(-1,-1, 0).uv(math::uv(t, s));
		*m_VB += vertex( 1,-1, 0).uv(math::uv(s, s));
		*m_VB += vertex( 1, 1, 0).uv(math::uv(s, t));
		*m_VB += vertex(-1, 1, 0).uv(math::uv(t, t));

		float n1 = -1.f;
		float p1 =  1.f;

		/**m_VB += vertex(n1,n1, 0).color(math::color3(1, 0, 0));
		*m_VB += vertex(p1,n1, 0).color(math::color3(0, 1, 0));
		*m_VB += vertex(p1,p1, 0).color(math::color3(0, 0, 1));
		*m_VB += vertex(n1,p1, 0).color(math::color3(1, 0, 0));*/

		*m_IB += 0;
		*m_IB += 1;
		*m_IB += 2;

		*m_IB += 0;
		*m_IB += 2;
		*m_IB += 3;
	}

	m_Mesh = new scene::mesh<api>(m_VB, m_IB);
//	m_Mesh->effects().push_back(
//		new texture_opengl(new view::canvas("./test_texture.tga"), 0));

	vertex::description_type d;
	std::cout << d;

	md5_builder<api> b("./q4/teleport_dropper.md5mesh");
	m_Model = b.build_model(*m_Default->m_Renderer);

	int tris = 0;
	for(int i = 0; i < m_Model.m_Meshes.size(); i++)
		tris += m_Model.m_Meshes[i]->tri_count();

	std::cout << "Triangles " << tris << std::endl;
}

void state_intro::activate(){}

void state_intro::deactivate(){}

void state_intro::tick(float a_DeltaTime){
	static int i = 0;
	static float dt = 0;
	i++;
	dt += a_DeltaTime;
	if(i > 1023){
		dt /= i;

		std::cout << (1.f / dt) << " fps" << std::endl;

		dt = 0;
		i = 0;
	}
	m_Default->m_Renderer->begin_scene(); // RAII this?

//	math::matrix m;
	static float f = 0;
	//f += a_DeltaTime;
	f = 2;

	
	math::matrix m;
	m.scale(0.01f);
	m.set_translation(math::vector3f(0, 0, 5));
	
	//m.concatenate(q);
	//math::matrix s;
	//s.rotate_y(f);
	//m.concatenate(s);

	//m_Default->m_Renderer->draw(*m_Mesh, m);
	
	for(int i = 0; i < m_Model.m_Meshes.size(); i++)
		m_Default->m_Renderer->draw(*m_Model.m_Meshes[i], m);

	m_EventLoop.update(); // we would rather not have this here!
	m_Default->m_Renderer->end_scene();

	//std::cout << "end_scene()" << std::endl;
}
